package cn.tangshh.universal.core.api;

import cn.hutool.core.collection.ListUtil;
import cn.tangshh.universal.core.util.MessageUtil;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.http.HttpStatus;

import java.util.Collection;

/**
 * 集合返回数据
 *
 * @author Tang
 * @version v1.0
 * @since 2024/05/30
 */
@Data
@Schema(title = "集合返回数据")
@EqualsAndHashCode(callSuper = true)
public final class LR<T> extends R<Collection<T>> {
    public static <T> LR<T> ok() {
        RCode success = RCode.SUCCESS;
        LR<T> lr = new LR<>();
        lr.setData(ListUtil.empty());
        lr.setMsg(MessageUtil.convert(success.getMessage()));
        lr.setCode(success);
        lr.setSuccess(true);
        return lr;
    }

    public static <T> LR<T> ok(String msg) {
        RCode success = RCode.SUCCESS;
        LR<T> lr = new LR<>();
        lr.setData(ListUtil.empty());
        lr.setMsg(MessageUtil.convert(msg));
        lr.setCode(success);
        lr.setSuccess(true);
        return lr;
    }

    public static <T> LR<T> ok(Collection<T> data) {
        LR<T> ok = ok();
        ok.setData(data);
        return ok;
    }

    public static <T> LR<T> ok(Collection<T> data, String msg) {
        RCode success = RCode.SUCCESS;
        LR<T> lr = new LR<>();
        lr.setData(data);
        lr.setMsg(MessageUtil.convert(msg));
        lr.setCode(success);
        lr.setSuccess(true);
        return lr;
    }

    public static <T> LR<T> fail() {
        RCode fail = RCode.BAD_REQUEST;
        LR<T> lr = new LR<>();
        lr.setMsg(MessageUtil.convert(fail.getMessage()));
        lr.setCode(fail);
        lr.setSuccess(false);
        return lr;
    }


    public static <T> LR<T> fail(String msg) {
        RCode fail = RCode.BAD_REQUEST;
        LR<T> lr = new LR<>();
        lr.setMsg(MessageUtil.convert(msg));
        lr.setCode(fail);
        lr.setSuccess(false);
        return lr;
    }

    public static <T> LR<T> of(RCode rCode) {
        LR<T> lr = new LR<>();
        lr.setMsg(MessageUtil.convert(rCode.getMessage()));
        lr.setCode(rCode);
        lr.setSuccess(rCode.getCode() <= 300);
        return lr;
    }

    public static <T> LR<T> of(HttpStatus status) {
        LR<T> lr = new LR<>();
        lr.setMsg(status.getReasonPhrase());
        lr.setCode(RCode.of(status.value()));
        lr.setSuccess(status.is2xxSuccessful());
        return lr;
    }
}